package com.zyp.demo.web;

import com.zyp.demo.service.BlogService;
import com.zyp.demo.service.TagsService;
import com.zyp.demo.service.TypeService;
import javassist.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class IndexController {
    @Autowired
    private BlogService blogService;
    @Autowired
    private TypeService typeService;
    @Autowired
    private TagsService tagsService;
    @GetMapping("/")
    public String index(@PageableDefault(size = 3,sort = {"updateTime"},
            direction = Sort.Direction.DESC)Pageable pageable, Model model){
        model.addAttribute("page",blogService.listBlog(pageable));
        model.addAttribute("types",typeService.listTypeTop(6));
        model.addAttribute("tags",tagsService.listTagTop(8));
        model.addAttribute("recommendBlogs",blogService.listRecommendBlogTop(8));
        return "index";
    }
    @PostMapping("/search")
    public String search(@RequestParam String query, @PageableDefault(size=3,sort ={"updateTime"},
            direction = Sort.Direction.DESC) Pageable pageable,Model model){
        model.addAttribute("page",blogService.listBlog(pageable,"%"+query+"%"));
        model.addAttribute("pages",blogService.listBlog(pageable));
        model.addAttribute("query",query);
        return "search";
    }
    @GetMapping("/blog/{id}")
    public String bloginfo(@PathVariable Long id,Model model,@PageableDefault(size=3,sort ={"updateTime"},
            direction = Sort.Direction.DESC) Pageable pageable) throws NotFoundException {
        model.addAttribute("blog",blogService.getAndConvertHtml(id));
        model.addAttribute("pages",blogService.listBlog(pageable));
        return "blog";
    }
}
